// index.js
const api = require('../../utils/api');
const { checkLogin, setLoginState } = require('../../utils/auth');

Page({
  data: {
    banners: [],
    products: [],
    hasUserInfo: false,
    userInfo: {},
    openid: '',
    token: '',
    isLoading: false,
    showAuthPopup: false,
    popupUserInfo: null
  },
  onLoad: function() {
    this.loadData();
    this.checkLogin();
  },
  onShow() {
    // 每次显示页面时检查登录状态
    this.checkLogin();
  },
  loadData: async function() {
    try {
      const [bannersRes, productsRes] = await Promise.all([
        api.getBanners(),
        api.getProducts()
      ]);
      this.setData({
        banners: bannersRes.banners,
        products: productsRes.products
      });
    } catch (error) {
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    }
  },
  showAuthPopup() {
    // 优先取本地 userInfo
    const userInfo = wx.getStorageSync('userInfo') || null;
    this.setData({ showAuthPopup: true, popupUserInfo: userInfo });
  },
  closeAuthPopup() {
    this.setData({ showAuthPopup: false });
  },
  handleAuthLogin() {
    if (this.data.isLoading) return;
    this.setData({ isLoading: true });
    wx.getUserProfile({
      desc: '用于完善会员资料',
      lang: 'zh_CN',
      success: async (userProfile) => {
        try {
          const loginRes = await wx.login();
          if (!loginRes.code) throw new Error('获取登录码失败');
          const res = await api.login({
            code: loginRes.code,
            userInfo: userProfile.userInfo
          });
          if (!setLoginState(res)) throw new Error('保存登录状态失败');
          this.setData({
            hasUserInfo: true,
            userInfo: res.userInfo,
            openid: res.openid,
            token: res.token,
            showAuthPopup: false,
            popupUserInfo: res.userInfo
          });
          wx.showToast({ title: '登录成功', icon: 'success', duration: 1500 });
        } catch (e) {
          wx.showToast({ title: e.errMsg || '登录失败', icon: 'error', duration: 2000 });
        } finally {
          this.setData({ isLoading: false });
        }
      },
      fail: () => {
        wx.showToast({ title: '用户拒绝授权', icon: 'none' });
        this.setData({ isLoading: false, showAuthPopup: false });
      }
    });
  },
  checkLogin() {
    if (checkLogin()) {
      const userInfo = wx.getStorageSync('userInfo');
      const token = wx.getStorageSync('token');
      this.setData({
        hasUserInfo: true,
        userInfo,
        token
      });
    }
  },
  onPullDownRefresh: function() {
    this.loadData().then(() => {
      wx.stopPullDownRefresh();
    });
  }
});
